<template>
  <div class="clearfix">
    <a-upload
      :action="actionUrl"
      list-type="picture-card"
      :file-list="fileList"
      @preview="handlePreview"
      @change="handleChange"
      :before-upload="beforeUpload"
      :remove="handRemove"
      :multiple="true"
      :accept="'image/*'"
    >
      <div v-if="fileList.length < 8">
        <a-icon type="plus" />
        <div class="ant-upload-text">Upload</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
import axios from 'axios'

export default {
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      actionUrl: '',
      delFIleName: '', //删除的文件路径
      isAllowUpload: false, //是否允许上传
    }
  },
  props: {
    model: {
      type: String,
      default: '',
    },
    isOpen: {
      type: Boolean,
      default: false,
    },
    imageArr: {
      type: [Array, String],
      default: () => [],
    },
    doType: {
      type: String,
      default: '',
    },
  },

  watch: {
    isOpen() {},
    // fileList() {
    //   console.log('fileList :>> ', this.fileList)
    // },
    imageArr() {
      console.log('this.imageArr :>> ', this.imageArr)
      if (!this.imageArr || this.imageArr.length <= 0) {
        return
      }
      if (this.imageArr.length > 0 && this.fileList.length <= 0) {
        this.imageArr.map((item, index) => {
          let a = {
            uid: item,
            name: 'xxx.png',
            status: 'done',
            url: item,
          }
          this.fileList.push(a)
          this.$forceUpdate()
        })
      }
    },
    doType(val) {
      console.log('type :>> ', this.doType)
      if (val == 'add') {
        this.fileList = []
      }
    },
  },
  created() {},

  mounted() {
    if (this.imageArr.length > 0) {
      this.fileList = []
      this.imageArr.map((item, index) => {
        let a = {
          uid: item,
          name: 'xxx.png',
          status: 'done',
          url: item,
        }
        this.fileList.push(a)
      })
    }
    this.actionUrl = this.$host + '/api/UploadFile'
  },

  methods: {
    // 上传前对文件大小和格式做检测
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        var testmsg = /^image\/(jpeg|png|jpg)$/.test(file.type)
        const isLt5M = file.size / 1024 / 1024 <= 5 //图片大小不超过5MB
        if (!testmsg) {
          this.$message.error(
            'Only JPG, JPEG, GIF and PNG images can be uploaded!'
          )
          return reject(false)
        }
        if (!isLt5M) {
          this.$message.error(
            'The size of the uploaded picture should not exceed 5M!'
          )
          return reject(false)
        }
        return resolve(true)
      })
    },
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange(info) {
      const that = this
      this.fileList = info.fileList
      info.model = this.model
      console.log('this.fileList :>> ', this.fileList)
      this.$emit('uploadFileList', info) //实时返回现有文件list
      if (info.file.status === 'done') {
        console.log('上传完:>> ', info)
      }
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = (error) => reject(error)
      })
    },
    uploadImg() {
      const data = {}
    },
    handRemove(file) {
      console.log('删除', file, '现有的文件', this.fileList)
      if (file.response) {
        this.deleteFile(file.response.data.fileName)
      } else if (file.url) {
        this.deleteFile(file.url)
      }
    },
    // 删除文件
    deleteFile(fileName) {
      const a = {
        method: 'DelFile',
        userId: window.userId || 1,
        sign: '1',
        currentPage: 0,
        limit: 0,
        datas: {
          fullFileName: fileName,
        },
      }
      const url = this.$host + '/api/DelFile'
      axios.post(url, JSON.stringify(a)).then((res) => {
        if (res.data.code === 0) {
          console.log('删除成功')
          this.$message.success('Delete Success!')
        } else {
          console.log('删除失败')
        }
      })
    },
    //返回一个 promise：检测通过则返回resolve；失败则返回reject，并阻止图片上传  [检测文件大小]
    checkImageWH(file) {
      const self = this
      return new Promise(function (resolve, reject) {
        const filereader = new FileReader()
        filereader.onload = (e) => {
          const src = e.target.result
          const image = new Image()
          image.onload = function () {
            // 获取图片的宽高，并存放到file对象中
            console.log('file width :' + this.width)
            console.log('file height :' + this.height)
            file.width = this.width
            file.height = this.height
            resolve()
          }
          image.onerror = reject
          image.src = src
        }
        filereader.readAsDataURL(file)
      })
    },
  },
}
</script>
<style lang="less" scoped>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>